<?php

namespace maotool\core\console\command\thread;

use Exception;
use maotool\core\console\Command;
use maotool\core\facade\Config;
use maotool\file\DirUtil;
use maotool\file\FileUtil;
use maotool\util\PathUtil;

class Thread extends Command
{
    public function getName()
    {
        // TODO: Implement getName() method.
    }

    public function getDescription()
    {
        // TODO: Implement getDescription() method.
    }

    public function getHelp($argv = [])
    {
        return "thread 进程";
    }

    public function getUsage($argv = [])
    {
        // TODO: Implement getUsage() method.
    }

    public function isHit($argv = [])
    {
        if (count($argv) > 1 && $argv[1] == "thread") {
            return true;
        }
        return false;
    }

    public function handle($argv = [])
    {
        echo "守护进程已开启 \n\n";
        while (true) {
            $path = Config::get("framework.runtime.thread.path");
            $files = DirUtil::scanFiles($path . "/task/**/*.thread");
            foreach ($files as $file) {
                if (is_file($file["path"])) {
                    $handle = fopen($file["path"], 'r+');
                    if (flock($handle, LOCK_EX | LOCK_NB)) {
                        if (filesize($file["path"])) {
                            $script = fread($handle, filesize($file["path"]));
                            $closure = unserialize($script)->getClosure();
                            $uid = substr($file["relativePath"], 5, 2) . substr($file["relativePath"], 8, 30);
                            $dirPath = PathUtil::path($path, "result", substr($uid, 0, 2));
                            $filePath = PathUtil::path($dirPath, substr($uid, 2) . ".thread");
                            DirUtil::create($dirPath);
                            try {
                                $result = $closure();
                                echo "进程返回数据 " . json_encode($result) . " \n";
                            } catch (Exception $e) {
                                $result = null;
                            }
                            FileUtil::write($filePath, serialize($result));
                        }
                        unlink($file["path"]);
                        flock($handle, LOCK_UN);
                        echo "已收到发送的进程数据 \n";
                    }
                    fclose($handle);
                }
            }
            echo "运行中 \n";
            sleep(1);
        }
    }
}